
import 'dart:async';

import 'val_data_base_constant.dart';
import 'val_data_base_core.dart';
import './val_data_base_frame_object.dart';

/// 实体
class ValDataBaseEntity {
  /// 表名
  final String dbTableName;
  /// 主键
  final String primaryKey;
  /// 查询的key
  final  Map<String, ValDataBaseQueryEnum> queryKeys;

  /// 初始化key
  late final ValDataBaseFrameObject _dbObject;

  ValDataBaseEntity({
    required this.dbTableName,
    required this.primaryKey,
    required this.queryKeys,
  }) {
    _init();
  }

  void _init() {
    _dbObject = ValDataBaseFrameObject();
    _dbObject.primaryKey = primaryKey;
    _dbObject.dbTableName = dbTableName;
    _dbObject.queryKeys = queryKeys;
    ValDataBaseCore().setupObjectDb(_dbObject);
  }


  /// 保存数据
  Future<void> save(ValDataBaseEntityInterface? data) async {
    if (data == null) return;
    _dbObject.dbData = data.dbOriginData();
    _dbObject.queryValues = data.queryValues();
    await ValDataBaseCore.saveObject(_dbObject);
  }

  /// 查询数据
  Future<List<Map>> get(
      { List <VaDataBaseQuery>? query,
        String? orderKey,
        bool isDesc = true,
        int? limitCount,
      }
      ) async {
    Completer<List<Map>> completer = Completer();
    ValDataBaseCore.getObjects(_dbObject.dbTableName,
        query:query,
            (value) => completer.complete(value),
        orderKey: orderKey,
        isDesc: isDesc,
        limitCount: limitCount
    );
    return completer.future;
  }

  /// 删除数据
   Future<bool> delete(
      String dbName,
      List <VaDataBaseQuery> conditions,
      ) async {
    return await ValDataBaseCore.delete(dbName, conditions);
  }

  ///  添加索引
  Future<void> addQueryIndex(String indexName,List<String> indexKeys) async {
    _dbObject.indexNameKey = indexName;
    _dbObject.indexKeys = indexKeys;
    await ValDataBaseCore.addIndex(_dbObject);
  }
}

abstract class ValDataBaseEntityInterface {

  /// 主key
  static const String primaryKey = '';

  /// 原始数据数据
  Map<String, dynamic> dbOriginData() {
    return {};
  }

  /// 查询的数据的值(元数据中如果没有，需要在这里补充)
  Map<String, dynamic>? queryValues() {
    return {};
  }

  /// 查询数据的key
  static Map<String, ValDataBaseQueryEnum> queryKeys() {
    return {};
  }
}